/**
 * 权限管理工具类
 * 用于检查用户对特定菜单的读写权限
 */

import axios from 'axios'
import { ref } from 'vue'

interface MenuPermission {
  menu_path: string
  can_read: boolean
  can_write: boolean
}

interface UserPermissions {
  [menuPath: string]: MenuPermission
}

class PermissionManager {
  private userPermissions: UserPermissions = {}
  private permissionsLoaded = false
  private loadingPromise: Promise<void> | null = null

  /**
   * 加载当前用户的权限
   */
  async loadUserPermissions(): Promise<void> {
    if (this.permissionsLoaded) {
      return
    }

    if (this.loadingPromise) {
      return this.loadingPromise
    }

    this.loadingPromise = this._loadPermissions()
    await this.loadingPromise
    this.loadingPromise = null
  }

  private async _loadPermissions(): Promise<void> {
    try {
      // 获取当前用户信息
      const userResponse = await axios.get('/api/users/current/')
      const currentUser = userResponse.data

      // 获取用户的所有权限
      const permissionsResponse = await axios.get('/api/menupermissions/get_user_permissions/')
      const permissions = permissionsResponse.data

      console.log('用户权限数据:', permissions)

      // 构建权限映射
      this.userPermissions = {}
      permissions.forEach((perm: any) => {
        this.userPermissions[perm.menu_path] = {
          menu_path: perm.menu_path,
          can_read: perm.can_read,
          can_write: perm.can_write
        }
      })

      this.permissionsLoaded = true
      console.log('权限加载完成:', this.userPermissions)
    } catch (error) {
      console.error('加载用户权限失败:', error)
      // 如果加载失败，给予默认权限（只读）
      this.userPermissions = {}
      this.permissionsLoaded = true
    }
  }

  /**
   * 检查对指定菜单路径的读权限
   */
  async canRead(menuPath: string): Promise<boolean> {
    await this.loadUserPermissions()

    const permission = this.userPermissions[menuPath]
    if (!permission) {
      // 如果没有找到权限配置，默认允许读取
      console.warn(`未找到菜单 ${menuPath} 的权限配置，默认允许读取`)
      return true
    }

    return permission.can_read
  }

  /**
   * 检查对指定菜单路径的写权限
   */
  async canWrite(menuPath: string): Promise<boolean> {
    await this.loadUserPermissions()

    const permission = this.userPermissions[menuPath]
    if (!permission) {
      // 如果没有找到权限配置，默认不允许写入
      console.warn(`未找到菜单 ${menuPath} 的权限配置，默认不允许写入`)
      return false
    }

    return permission.can_write
  }

  /**
   * 检查是否可以执行指定操作
   */
  async canPerformAction(menuPath: string, action: 'read' | 'write' | 'create' | 'update' | 'delete'): Promise<boolean> {
    switch (action) {
      case 'read':
        return await this.canRead(menuPath)
      case 'write':
      case 'create':
      case 'update':
      case 'delete':
        return await this.canWrite(menuPath)
      default:
        return false
    }
  }

  /**
   * 获取菜单权限信息
   */
  async getMenuPermission(menuPath: string): Promise<MenuPermission | null> {
    await this.loadUserPermissions()
    return this.userPermissions[menuPath] || null
  }

  /**
   * 刷新权限缓存
   */
  refreshPermissions(): void {
    this.permissionsLoaded = false
    this.userPermissions = {}
    this.loadingPromise = null
  }

  /**
   * 获取所有权限
   */
  async getAllPermissions(): Promise<UserPermissions> {
    await this.loadUserPermissions()
    return { ...this.userPermissions }
  }
}

// 创建单例实例
export const permissionManager = new PermissionManager()

/**
 * Vue 组合式 API 钩子
 */
export function usePermission() {
  return {
    canRead: (menuPath: string) => permissionManager.canRead(menuPath),
    canWrite: (menuPath: string) => permissionManager.canWrite(menuPath),
    canPerformAction: (menuPath: string, action: 'read' | 'write' | 'create' | 'update' | 'delete') =>
      permissionManager.canPerformAction(menuPath, action),
    getMenuPermission: (menuPath: string) => permissionManager.getMenuPermission(menuPath),
    refreshPermissions: () => permissionManager.refreshPermissions(),
    getAllPermissions: () => permissionManager.getAllPermissions()
  }
}

/**
 * 页面权限控制 Hook
 * 用于管理页面的增删改查权限
 */
export function usePagePermission(menuPath: string) {
  const { canRead, canWrite } = usePermission()
  const canReadPage = ref(true)
  const canWritePage = ref(true)
  const permissionsLoaded = ref(false)

  const checkPermissions = async () => {
    try {
      canReadPage.value = await canRead(menuPath)
      canWritePage.value = await canWrite(menuPath)
      permissionsLoaded.value = true
      console.log(`页面权限检查 ${menuPath}:`, {
        canRead: canReadPage.value,
        canWrite: canWritePage.value
      })
    } catch (error) {
      console.error('权限检查失败:', error)
      canReadPage.value = false
      canWritePage.value = false
      permissionsLoaded.value = true
    }
  }

  return {
    canReadPage,
    canWritePage,
    permissionsLoaded,
    checkPermissions
  }
}

/**
 * 权限指令，用于在模板中控制元素显示
 */
export const permissionDirective = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding
    if (!value) return

    const { menuPath, action = 'read' } = value

    permissionManager.canPerformAction(menuPath, action).then(hasPermission => {
      if (!hasPermission) {
        el.style.display = 'none'
      }
    })
  },

  updated(el: HTMLElement, binding: any) {
    const { value } = binding
    if (!value) return

    const { menuPath, action = 'read' } = value

    permissionManager.canPerformAction(menuPath, action).then(hasPermission => {
      if (!hasPermission) {
        el.style.display = 'none'
      } else {
        el.style.display = ''
      }
    })
  }
}

export default permissionManager
